﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace TL_Cloud.Utils
{
    /// <summary>
    /// 短信配置模板
    /// </summary>
    public class SmsHelper
    {
        /// <summary>
        /// 短信平台地址
        /// </summary>
        private string SMSUrl = "";
        /// <summary>
        /// 账户
        /// </summary>
        private string SMSAccount = "";
        /// <summary>
        /// 密码
        /// </summary>
        private string SMSPwd = "";
        /// <summary>
        /// 签名
        /// </summary>
        private string SMSSign = "";
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SMSURL"></param>
        /// <param name="SMSAccount"></param>
        /// <param name="SMSPwd"></param>
        /// <param name="SMSSign"></param>
        public SmsHelper(string SMSURL,string SMSAccount,string SMSPwd, string SMSSign)
        {
            this.SMSUrl = SMSURL;
            this.SMSAccount = SMSAccount;
            this.SMSPwd = SMSPwd;
            this.SMSSign = SMSSign;
        }
        #region 短信平台

        public string SendSms(string number, string message, Dictionary<string, string> dictsURLExtends)
        {

            //<add key="SMSURL" value="http://www.ztsms.cn:8800/sendNSms.do"/>
            //<!-- 短信账户 -->
            //<add key="SMSAccount" value="shunshi888" />
            //<!-- 短信密码 -->
            //<add key="SMSPwd" value="Gxf1985412" /> 
            //<!--短信通知通道-->
            //<add key="SMSNoticePassageway" value="887362"/>
            //<!--短信验证码通道-->
            //<add key="SMSVerificationCodePassageway" value="676767"/>

            string smsapi = SMSUrl;
            string smsname = SMSAccount;
            string smspass = SMSPwd;
            string sign = SMSSign;

            string tkey = DateTime.Now.ToString("yyyyMMddHHmmss");
            string password = Md5(Md5(smspass) + tkey);

            string url = smsapi + "?username=" + smsname
                + "&password=" + password + "&mobile="
                + number + "&content=" + message + sign + "&tkey="
                + tkey + "&xh=";
            foreach (var item in dictsURLExtends)
            {
                if (url.IndexOf("?") >= 0)
                {
                    url += $"&{item.Key}={item.Value}";
                }
                else
                {
                    url +=  $"?{item.Key}={item.Value}";
                }
            }

            WebRequest _request = WebRequest.Create(url);
            Task<WebResponse> _response = _request.GetResponseAsync();
            Stream stream = _response.Result.GetResponseStream();
            StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
            string r = reader.ReadToEnd();
            int len = r.Split(',').Length;
            string msg = "";
            switch (len)
            {
                case 1:
                    switch (r)
                    {
                        case "-1":
                            msg = "用户名或者密码不正确或用户禁用或者是管理账户";
                            break;
                        case "2":
                            msg = "余额不够或扣费错误";
                            break;
                        case "3":
                            msg = "扣费失败异常（请联系客服）";
                            break;
                        case "6":
                            msg = "有效号码为空";
                            break;
                        case "7":
                            msg = "短信内容为空";
                            break;
                        case "8":
                            msg = "无签名，必须，格式：【签名】";
                            break;
                        case "9":
                            msg = "没有Url提交权限";
                            break;
                        case "10":
                            msg = "发送号码过多,最多支持2000个号码";
                            break;
                        case "11":
                            msg = "产品ID异常或产品禁用";
                            break;
                        case "12":
                            msg = "参数异常";
                            break;
                        case "15":
                            msg = "Ip验证失败";
                            break;
                        case "19":
                            msg = "短信内容过长，最多支持500个,或提交编码异常导致";
                            break;
                        default:
                            msg = "未知错误";
                            break;
                    }
                    break;
                case 2:
                    //成功
                    msg = string.Empty;
                    //1,xxxxxxxx 1代表发送短信成功,xxxxxxxx代表消息编号（消息ID,在匹配状态报告时会用到）
                    string[] temp = r.Split(',');
                    switch (temp[0])
                    {
                        case "0":
                            msg = "发送短信失败:" + temp[1];
                            break;
                        case "1": //1代表发送短信成功,xxxxxxxx代表消息编号（消息ID,在匹配状态报告时会用到）
                            msg = "";
                            break;
                        default:
                            msg = "未知错误";
                            break;
                    }
                    break;
                default:
                    msg = "发送短信异常!";
                    break;
            }
            return msg; 
        }
        #endregion
        private static string Md5(string value)
        {
            byte[] result;

            using (MD5 md5 = MD5.Create())
            {
                result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value));
            }

            return BitConverter.ToString(result).Replace("-", "").ToLower();
        }
    }
}
